﻿using IServices;
using System;
using System.Collections.Generic;
using System.Text;
using YL.Core.Entity;
using SqlSugar;
using IRepository;
using YL.Utils.Extensions;

namespace Services
{
    public class Whr_user_refresh_tokenServices : BaseServices<Whr_user_refresh_token>, IWhr_user_refresh_tokenServices
    {
        private readonly IWhr_user_refresh_tokenRepository _repository;
        private readonly SqlSugarClient _client;
        public Whr_user_refresh_tokenServices(SqlSugarClient client, IWhr_user_refresh_tokenRepository repository) : base(repository)
        {
            _repository = repository;
            _client = client;
        }

        /// <summary>
        /// 验证刷新token是否存在或过期
        /// </summary>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public bool IsValidRefreshToken(string refreshToken)
        {
            return _repository.IsAny(d => d.RefreshToken.Equals(refreshToken) && d.Expired  >= DateTimeExt.GetUnixTimestamp());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="days"></param>
        /// <returns></returns>
        public bool CreateRefreshToken(string token, int userId, double days = 15)
        {
            return _repository.Insert(new Whr_user_refresh_token { RefreshToken = token, UserId = userId, Expired = DateTimeExt.GetUnixTimestamp() + 86400 * (int)days });
        }

        public bool RemoveRefreshToken(string refreshToken) 
        {
            return _repository.Delete(d => d.RefreshToken.Equals(refreshToken));
        }

        public bool RemoveRefreshTokenByUserId(int userId) 
        {
            return _repository.Delete(d => d.UserId == userId);
        }
    }
}
